package com.maizhi.controller;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.maizhi.hr.model.HrLwImp;
import com.maizhi.hr.model.imgConfig;
import com.maizhi.hr.model.imgItem;
import com.maizhi.hr.model.txtConfig;
import com.maizhi.httpmodel.Json;
import com.maizhi.model.Files;
import com.maizhi.service.FilesServiceI;
import com.maizhi.util.StringUtil;
import com.maizhi.util.xlsxUtil;

@Controller
@RequestMapping("/impController")
public class impController extends BaseController {

	Logger logger = Logger.getLogger(impController.class);
	
	FilesServiceI fileService;
	
	public FilesServiceI getFileService() {
		return fileService;
	}


	@Autowired
	public void setFileService(FilesServiceI fileService) {
		this.fileService = fileService;
	}
	
	
	@RequestMapping(params = "wxImpl")
	@ResponseBody
	public Json wxImpl(String saveFileId){
		logger.info("导入文件： "+saveFileId);
		Json json = new Json();
		try{
			if(saveFileId!=null && !saveFileId.equals("")){
				Files files = (Files) fileService.get(Files.class, saveFileId);
				logger.info("files : "+files.getFileName());
				if(files!=null){
					String subfix = files.getFileSubffix().toUpperCase(); 
					logger.info("后缀： "+subfix);
					if(subfix.equals(".XLS") || subfix.equals(".XLSX")){
						wxImplMehod2(files);
						json.setSuccess(true);
						json.setMsg("导入完成");
					}
				}
			}
		}catch(Exception e){
			json.setMsg("导入数据异常:"+e.getMessage());
			e.printStackTrace();
		}
		return json;
	}


	public int wxImplMehod(Files file) {
		int n=0;
		boolean flag=true;
		File f=null;
		if(file!=null){
			f=new File(file.getFilePath()+"\\"+file.getFlagName());
		}
		try{
		Date logDate = new Date();
		xlsxUtil xlsxu = new xlsxUtil();
		List<List<String>> res= xlsxu.parseXlsXlsxByPoi(f);
			if(res!=null && res.size()>0){
				for(int i=0;i<res.size();i++){
					List<String> row = res.get(i);
					if(row!=null && row.size()>0){
						try{
							for(int k=0;k<row.size();k++){
								logger.info(i+" : "+k+"  : "+StringUtil.nullTrim(row.get(k)));
							}
						}catch(Exception e){
							//logger.error("数据读入异常 ： "+e.getMessage());
						}
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error("导入数据异常： "+e.getMessage());
		}
		return n;
	}
	
	
	public int wxImplMehod2(Files file) {
		int n=0;
		boolean flag=true;
		File f=null;
		if(file!=null){
			f=new File(file.getFilePath()+"\\"+file.getFlagName());
		}
		try{
			Date logDate = new Date();
			xlsxUtil xlsxu = new xlsxUtil();
			Map<String,List<String>> res= xlsxu.parseXlsXlsxByPoi2(f);
			
			 
			  
			Iterator iter = res.entrySet().iterator();
		    //通过ArrayList构造函数把map.entrySet()转换成list 
		    List<Map.Entry<String,List<String>>> mappingList = new ArrayList<Map.Entry<String,List<String>>>(res.entrySet()); 
		    //通过比较器实现比较排序 
		    Collections.sort(mappingList, new Comparator<Map.Entry<String,List<String>>>(){ 
			   public int compare(Map.Entry<String,List<String>> mapping1,Map.Entry<String,List<String>> mapping2){
				int k1 = Integer.parseInt(mapping1.getKey().substring(mapping1.getKey().lastIndexOf(":")+1));
				int k2 = Integer.parseInt(mapping2.getKey().substring(mapping2.getKey().lastIndexOf(":")+1));
				return k1 - k2;
			  } 
			});
		    
		    
		    txtConfig txt=null;
		    imgConfig img=null;
		    imgItem   iimg=null;
		    String    sheetName="";
		    List<imgItem> iitems=new ArrayList<imgItem>();
		    
		    try{
			    for(Map.Entry<String,List<String>> mapping:mappingList){ 
		    	    String key = (String)mapping.getKey();
		    	    logger.info("key : "+key);
		    	    
		    	    logger.info("sheetName : "+sheetName+" NewSheetName : "+key.substring(key.indexOf(":")+1,key.lastIndexOf(":")));
		    	    
		    	    if(!key.substring(key.indexOf(":")+1,key.lastIndexOf(":")).equals(sheetName)){
		    	    	sheetName=key.substring(key.indexOf(":")+1,key.lastIndexOf(":"));
		    	    	txt=null;
						img=null;
						iimg=null;
						iitems=new ArrayList<imgItem>();
		    	    } 
		    	    
					List<String> row = (List<String>)mapping.getValue();
					if(row!=null && row.size()>0){
							String FlagCell="";
							FlagCell = StringUtil.nullTrim(row.get(1));
							//logger.info(key+" - "+k+" - "+StringUtil.nullTrim(row.get(k)));
							if(FlagCell.indexOf("TEXT")>=0){
								txt = (txt==null?new txtConfig():txt);
								txt.setId(StringUtil.uuid());
								txt.setName(key);
								txt.setStatus(1);
							}else if(FlagCell.indexOf("IMAGE")>=0){
								img = (img==null?new imgConfig():img);
								img.setId(StringUtil.uuid());
								img.setName(key);
								img.setStatus(1);
							}else if(FlagCell.indexOf("图文标题")>=0){
								iimg = (iimg==null?new imgItem():iimg);
								iimg.setId(StringUtil.uuid());
								iimg.setName(key);
								iimg.setStatus(1);
							}
							
							if(txt!=null){
								if(StringUtil.nullTrim(row.get(0)).indexOf("发送")>=0)
									txt.setMsg(StringUtil.nullTrim(row.get(1)));
								if(StringUtil.nullTrim(row.get(0)).indexOf("回复")>=0)
									txt.setText(StringUtil.nullTrim(row.get(1)));
							}
							
							if(img!=null){
									if(StringUtil.nullTrim(row.get(0)).indexOf("发送")>=0)
										img.setMsg(StringUtil.nullTrim(row.get(1)));
									if(StringUtil.nullTrim(row.get(0)).indexOf("标题")>=0)
										img.setTitle(StringUtil.nullTrim(row.get(1)));
									if(StringUtil.nullTrim(row.get(0)).indexOf("描述")>=0)
										img.setDescription(StringUtil.nullTrim(row.get(1)));
									if(StringUtil.nullTrim(row.get(0)).indexOf("图片链接")>=0)
										img.setPicUrl(StringUtil.nullTrim(row.get(1)));
									if(StringUtil.nullTrim(row.get(0)).indexOf("网址链接")>=0)
										img.setUrl(StringUtil.nullTrim(row.get(1)));
								if(iimg!=null){
									try{
										logger.info("*********** : "+Math.round(Double.parseDouble(StringUtil.nullTrim(row.get(0)))));
										if(Math.round(Double.parseDouble(StringUtil.nullTrim(row.get(0))))>=0){
											iimg.setId(img.getId());
											iimg.setSeq((int)Math.round(Double.parseDouble(StringUtil.nullTrim(row.get(0)))));
											iimg.setTitle(StringUtil.nullTrim(row.get(1)));
											iimg.setDescription(StringUtil.nullTrim(row.get(2)));
											iimg.setPicUrl(StringUtil.nullTrim(row.get(3)));
											iimg.setUrl(StringUtil.nullTrim(row.get(4)));
											iitems.add(iimg);
										}
									}catch(Exception e){
										//序列不为数字直接跳过
										logger.error("序列号不准确 : "+e.getMessage());
									}
								}
							}
					}
					//添加图文列表
					if(img!=null && iitems.size()>0){
						img.setImgItem(iitems);
					}
					
					
					logger.info(" txtConfig :"+txt+" : "+(txt==null?"":txt.getMsg()));
					logger.info(" imgConfig :"+img+" : "+(img==null?"":img.getTitle()));
					logger.info(" imgItem :"+iimg+" : "+(img==null?"":img.getTitle()));
					
					logger.info(" iitems : "+iitems+" size :"+(iitems==null?"":iitems.size()));
			    } 
		    }catch(Exception e){
				logger.error("数据读入异常 ： "+e.getMessage());
		    	e.printStackTrace();
			}finally{
				txt=null;
				img=null;
				iimg=null;
				iitems=null;
			}
			
		}catch(Exception e){
			e.printStackTrace();
			logger.error("导入数据异常： "+e.getMessage());
		}
		return n;
	}
	
	
}
